package com.imooc.controller;

import com.imooc.ResultEnum.ResultBoyEnum;
import com.imooc.domain.Boy;
import com.imooc.repository.BoyRepository;
import com.imooc.result.Result;
import com.imooc.result.ResultUtils;
import com.imooc.service.BoyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chenxin on 2017/4/30.
 */
@RestController
@RequestMapping("/boy")
public class BoyController {
    @Autowired
    private BoyService boyService;
    @Autowired
    private BoyRepository boyRepository;

    public final static Logger logger = LoggerFactory.getLogger(BoyController.class);

    //插入一条数据到数据库
    @PostMapping(value = "/savaone")
    //public Boy savaOne(@RequestParam("name") String name,@RequestParam("age") Integer age){
    public Result<Boy> savaOne(@Valid Boy boy, BindingResult bindingResult) {
//
//        Boy boy=new Boy();
//        boy.setName(name);
//        boy.setAge(age);
        if (bindingResult.hasErrors()) {
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            Map map = new HashMap();
            // return ResultUtils.error(ResultBoyEnum.ERROR.getCode(),ResultBoyEnum.ERROR.getMessage());
            return ResultUtils.error(ResultBoyEnum.ERROR.getCode(), ResultBoyEnum.ERROR.getMessage());
        }
        return ResultUtils.success(boyRepository.save(boy));
    }

}
